import React, { Component } from 'react'
import { nanoid } from 'nanoid';
import './css/index.css'

export default class App extends Component {
    state = {
        myText: "",
        list: [
            {
                id: nanoid(),
                name: "张三",
                isChecked: false,
            }
        ]
    }
    // textRef = React.createRef();
    render() {
        return (
            <div>
                <input value={this.state.myText} onChange={(evt) => {
                    this.setState({ myText: evt.target.value })
                }} /> <button onClick={() => this.add()}>添加</button>
                <ul>
                    {
                        this.state.list.map(
                            (item, index) =>
                                <li key={item.id}>
                                    <input type="checkbox" checked={item.isChecked} onChange={() => {
                                        this.handleChecked(index)
                                    }}/>
                                    {/* {item.name} */}
                                    {/* 富文本展示 */}
                                    <span dangerouslySetInnerHTML={
                                        {
                                            __html: item.name
                                        }
                                    } style={{textDecoration: item.isChecked ? "line-through" : ""}}></span>
                                    <button onClick={() => this.delList(index)}>删除</button>
                                </li>
                        )
                    }
                </ul>
                {/* 条件渲染：通过三目运算 */}
                {/* {this.state.list.length === 0 ? <div>暂无内容</div> : null} */}
                {this.state.list.length === 0 && <div>暂无内容</div>}
                {/* 可以通过样式来控制条件渲染，这种就是本身节点已经存在了，前面两种呢不显示就是节点不存在的 */}
                {/* <div className={this.state.list.length === 0 ? '' : 'hidden'}>暂无内容</div> */}
            </div>
        )
    }

    handleChecked = (index) => {
        let newList = [...this.state.list]
        newList[index].isChecked = !newList[index].isChecked
        this.setState({
            list: newList
        })
    }

    delList(index) {
        let newList = [...this.state.list]
        newList.splice(index, 1);
        this.setState({
            list: newList
        })
    }
    add() {
        // 深拷贝数组
        let newList = [...this.state.list]
        newList.push({
            id: nanoid(),
            name: this.state.myText,
            isChecked: false,
        })
        this.setState({
            myText: "",
            list: newList
        })
    }
}
